import jwt from "jsonwebtoken";
import {auth, userStatus} from "./config";
import rp from "request-promise";
import {createUser} from "./api/userApi";
function login(req, res, next) {
    // const userName = req.cookies.userName;
    const callbackUrl = req.body.callbackUrl;
    const opd = req.body.opd;
    const kgLoginTicket = req.body.kgLoginTicket;
    const redirectUrl =
        "http://opd.kugou.net/common/signinApi.php?appId=v1-59f6a2253c62a&url=" +
        encodeURIComponent("http://" + callbackUrl);
    if (kgLoginTicket) {
        rp({
            uri: "http://opi.kgidc.cn/user/user/get.php",
            qs: {
                kgLoginTicket: kgLoginTicket,
                appid: "v1-59f6a2253c62a",
                appsecret: "9c51f02d83b283d9fd277dd3281be244"
            },
            json: true
            // proxy: PROXY // IDC机器无需代理
        })
            .then(async repos => {
                try {
                    const userInfo = Object.assign({}, repos.data);
                    const user = await createUser({
                        ...userInfo,
                        role: userStatus.normal
                    });
                    const token = jwt.sign({data: user[0]}, auth.jwt.secret, {
                        expiresIn: "8h"
                    });
                    res.send({
                        token: token,
                        status: 1,
                        userInfo: user[0]
                    });
                } catch (error) {
                    console.log(error);
                    res.send({
                        status: 0,
                        token: "",
                        redirectUrl: redirectUrl,
                        msg: error.toString()
                    });
                }
            })
            .catch(error => {
                console.log(error);
                res.send({
                    status: 0,
                    token: "",
                    redirectUrl: redirectUrl
                });
            });
    } else if (opd) {
        const token = jwt.sign({data: JSON.parse(opd)}, auth.jwt.secret, {expiresIn: "8h"});
        res.send({
            token: token,
            status: 1,
            userInfo: opd
        });
    } else {
        res.send({
            status: 0,
            token: "",
            redirectUrl: redirectUrl
        });
    }
}
export default login;